package com.jzy.gulimall.product.exception;

import com.jzy.common.exception.BizCodeEnum;
import com.jzy.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jzy
 * @date 2020/9/6 9:55
 * 集中处理所有异常
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.jzy.gulimall.product.controller")
public class ProductExceptionControllerAdvice implements ResponseBodyAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerValidException(MethodArgumentNotValidException e) {
        log.info("数据校验出现问题{},异常类型{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        //1.获取校验的错误结果
        result.getFieldErrors().forEach(item -> {
            //2.FieldError获取到错误提示
            String message = item.getDefaultMessage();
            //3.获取错误的属性名字
            String field = item.getField();
            map.put(field, message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handlerException(Throwable throwable) {
        log.info(throwable.getMessage());
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(),BizCodeEnum.UNKNOWN_EXCEPTION.getMessage());
    }

    //返回结果是否增强
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    //返回结果如何增强
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return null;
    }
}
